package org.lzy.shop.order

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textview.MaterialTextView
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import kotlinx.coroutines.launch
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.adapter.MyOrderAdapter
import org.lzy.shop.base.BaseMvvmFragment
import org.lzy.shop.databinding.FragmentOrderBinding
import org.lzy.shop.datas.OrderRequest
import org.lzy.shop.good.GoodInfoActivity
import org.lzy.shop.response.OrderResponse
import org.lzy.shop.viewmodel.OrderModel

/**
 * 订单fragment
 */
class FragmentOrder : BaseMvvmFragment<FragmentOrderBinding, OrderModel>(FragmentOrderBinding::inflate), SwipeRefreshLayout.OnRefreshListener {

    // 常量定义
    companion object {
        private const val FIRST_PAGE = 1
        private const val PAGE_SIZE = 10
        private const val STATUS_KEY = "status"

        fun newInstance(status: IntArray?): FragmentOrder {
            val fragment = FragmentOrder()
            val bundle = Bundle()
            bundle.putIntArray(STATUS_KEY, status)
            fragment.arguments = bundle
            return fragment
        }
    }

    private var isLoadingMore = false
    private var hasMoreData = true // 标记是否有更多数据

    private var mPageIndex = FIRST_PAGE
    private var receiveStatus: IntArray? = null
    private val mOrderAdapter by lazy { MyOrderAdapter() }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        receiveStatus = arguments?.getIntArray(STATUS_KEY)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun initView() {
        binding.recyclerview.apply {
            layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
            adapter = mOrderAdapter
        }

        binding.refreshLayout.apply {
            setOnRefreshListener(this@FragmentOrder)
        }
    }



    override fun requestData() {
        getOrderList()
    }

    override fun initData() {
        observeViewModel()
        setupAdapterListeners()
    }

    // 使用协程处理网络请求
    private fun getOrderList() {
        /**
         * lifecycleScope.launch原因如下:
         * 避免阻塞主线程
         *
         * - 网络请求是耗时操作，如果在主线程执行会导致UI卡顿甚至ANR(应用无响应)
         * - 使用协程可以将网络请求放到后台线程执行，保持UI线程的流畅性
         * -生命周期绑定
         * - lifecycleScope 是 AndroidX Lifecycle 库提供的协程作用域
         * - 它会自动跟随 Fragment 的生命周期，当 Fragment 销毁时，所有通过 lifecycleScope 启动的协程都会被自动取消
         * - 这样可以防止内存泄漏，避免在 Fragment 已经销毁后还去更新UI或处理回调
         */
        lifecycleScope.launch {
            try {
                val orderRequest = OrderRequest().apply {
                    page = mPageIndex
                    size = PAGE_SIZE
                    status = receiveStatus
                }
                mViewModel.getOrder(orderRequest)
            } catch (e: Exception) {
                e.printStackTrace()
                finishRefresh()
                showErrorToast("获取订单列表失败")
            }
        }
    }

    // 观察ViewModel数据变化
    private fun observeViewModel() {
        // 订单列表回调
        mViewModel.orderListData.observeWithLifecycle(viewLifecycleOwner) {orderResponse ->
            finishRefresh()
            orderResponse?.let {
                val list = orderResponse.list
                list?.let {
                    if (list.isNotEmpty()) {
                        if (mPageIndex == FIRST_PAGE) {
                            mOrderAdapter.submitList(list)
                        } else {
                            mOrderAdapter.addAll(list)
                        }
                    } else {
                        if (mPageIndex > FIRST_PAGE) {
                            // 已加载全部数据，不做特殊处理
                        } else {
                            showListEmpty()
                        }
                    }

                }

            }
        }


        // 取消订单回调
        mViewModel.orderOpertionData.observeWithLifecycle(viewLifecycleOwner) {
            handleOperationResponse("取消订单成功")
        }

        // 确认收货回调
        mViewModel.orderConfirmData.observeWithLifecycle(viewLifecycleOwner) {
            handleOperationResponse("确认收货成功")
        }

        // 订单退款回调
        mViewModel.orderRefundData.observeWithLifecycle(viewLifecycleOwner) {
            handleOperationResponse("退款成功")
        }
    }

    // 设置适配器监听器
    private fun setupAdapterListeners() {
        // 取消订单
        mOrderAdapter.addOnItemChildClickListener(R.id.tv_cancel_order) { adapter, _, position ->
            adapter.getItem(position)?.let { cancelOrder(it.id) }
        }

        // 申请退款
        mOrderAdapter.addOnItemChildClickListener(R.id.tv_apply_return) { adapter, _, position ->
            adapter.getItem(position)?.let { navigateToRefund(it.id) }
        }

        // 再次购买
        mOrderAdapter.addOnItemChildClickListener(R.id.tv_buy_again) { adapter, _, position ->
            adapter.getItem(position)?.let { navigateToGoodDetail(it) }
        }

        // 确认收货
        mOrderAdapter.addOnItemChildClickListener(R.id.tv_confirm_deliver_goods) { adapter, _, position ->
            adapter.getItem(position)?.let { confirmOrder(it.id) }
        }

        // 查看物流
        mOrderAdapter.addOnItemChildClickListener(R.id.check_logistics_tv) { adapter, _, position ->
            adapter.getItem(position)?.let { navigateToLogistics(it.id) }
        }

        // 待评价
        mOrderAdapter.addOnItemChildClickListener(R.id.order_comment) { adapter, _, position ->
            adapter.getItem(position)?.let { navigateToComment(it.id, it.userId) }
        }

        // 点击列表跳订单详情
        mOrderAdapter.setOnItemClickListener { adapter, _, position ->
            adapter.getItem(position)?.let { navigateToOrderDetail(it) }
        }
    }



    // 处理操作响应
    private fun handleOperationResponse(message: String) {
        dismissLoadingDialog()
        showSuccessToast(message)
        getOrderList() // 重新获取订单列表
    }

    // 无数据底纹显示
    fun showListEmpty() {
        mOrderAdapter.submitList(null)
        mOrderAdapter.isStateViewEnable = true
        mOrderAdapter.stateView = showEmptyView()
    }

    // 取消订单确认
    fun cancelOrder(orderId: Int) {
        CustomDialog.show(object : OnBindView<CustomDialog?>(R.layout.dialog_input) {
            override fun onBind(dialog: CustomDialog?, v: View?) {
                val showText = v?.findViewById<TextInputEditText>(R.id.act_confirm_order_et_remark)
                val btnOk = v?.findViewById<MaterialTextView>(R.id.btn_pos)
                val btnCancel = v?.findViewById<MaterialTextView>(R.id.btn_neg)
                btnOk?.setOnClickListener {
                    if (TextUtils.isEmpty(showText?.text.toString())) {
                        showToast(getResString(R.string.refund_reason))
                    } else {
                        dialog?.dismiss()
                        showLoadingDialog()
                        lifecycleScope.launch {
                            try {
                                mViewModel.cancelOrder(orderId, showText?.text.toString())
                            } catch (e: Exception) {
                                e.printStackTrace()
                                dismissLoadingDialog()
                                showErrorToast("取消订单失败，请重试")
                            }
                        }
                    }
                }
                btnCancel?.setOnClickListener { dialog?.dismiss() }
            }
        }).setMaskColor("#4D000000".toColorInt())
    }

    // 订单退款
    fun navigateToRefund(orderId: Int) {
        val bundle = Bundle()
        bundle.putInt(Constant.ORDERID, orderId)
        startActivity(OrderRefundActivity::class.java, bundle)
    }

    // 确认收货订单对话框
    fun confirmOrder(orderId: Int) {
        CustomDialog.show(object : OnBindView<CustomDialog?>(R.layout.dialog_common) {
            override fun onBind(dialog: CustomDialog?, v: View?) {
                val showText = v?.findViewById<MaterialTextView>(R.id.txt_msg)
                val showTitle = v?.findViewById<MaterialTextView>(R.id.txt_title)
                showText?.text = getResString(R.string.confirm_order_hint)
                showTitle?.text = getResString(R.string.confirm_deliverygoods)
                val btnOk = v?.findViewById<MaterialTextView>(R.id.btn_pos)
                val btnCancel = v?.findViewById<MaterialTextView>(R.id.btn_neg)
                btnOk?.setOnClickListener {
                    dialog?.dismiss()
                    showLoadingDialog()
                    lifecycleScope.launch {
                        mViewModel.confirmOrder(orderId)
                    }
                }
                btnCancel?.setOnClickListener { dialog?.dismiss() }
            }
        }).setMaskColor("#4D000000".toColorInt())
    }

    // 导航到商品详情
    private fun navigateToGoodDetail(orderItem: Any) {
        val bundle = Bundle()
        // 正确解析OrderResponse.List对象获取goodsId
        runCatching {
            val orderList = orderItem as? OrderResponse.List
            orderList?.goodsList?.let { list ->
                // 取第一个商品ID（再次购买时通常只需要一个商品ID）
                val goodsId = list.getOrNull(0)?.goodsId ?: 0
                bundle.putInt(Constant.GOODID, goodsId)
            }
        }

        startActivity(GoodInfoActivity::class.java, bundle)
    }

    // 导航到物流页面
    private fun navigateToLogistics(orderId: Int) {
        val bundle = Bundle()
        bundle.putInt(Constant.ORDERID, orderId)
        startActivity(LogisticsListActivity::class.java, bundle)
    }

    // 导航到评价页面
    private fun navigateToComment(orderId: Int, userId: Int) {
        val bundle = Bundle()
        bundle.putInt(Constant.ORDERID, orderId)
        bundle.putInt(Constant.GOODID, userId) // 注意：这里可能有误，userId被用作GOODID
        startActivity(OrderCommentActivity::class.java, bundle)
    }

    // 导航到订单详情（也修复了类似问题）
    private fun navigateToOrderDetail(orderItem: Any) {
        val bundle = Bundle()

        // 正确获取订单ID和标题
        runCatching {
            val orderList = orderItem as? OrderResponse.List
            bundle.putInt(Constant.ORDERID, orderList?.id ?: 0)
            bundle.putString(Constant.GOODSTITLE, orderList?.title ?: "")
            orderList?.let {
                // 获取订单ID
                bundle.putInt(Constant.ORDERID, it.id)

                // 从订单的goodsList中获取第一个商品的ID
                val goodsId = it.goodsList?.getOrNull(0)?.goodsId ?: 0
                bundle.putInt(Constant.GOODID, goodsId)
            }
        }
        startActivity(OrderInfoActivity::class.java, bundle)
    }

    // 完成刷新
    private fun finishRefresh() {
        binding.refreshLayout.isRefreshing = false
    }

    override fun onRefresh() {
        mPageIndex = FIRST_PAGE
        getOrderList()

    }

    override fun allClick() {}
}